<template>
    <v-dialog-layout title="添加部门" width="500px" v-model:visible="visible" @confirm="formAdd.onSubmit()" @cancel="cancel">
        <v-form-layout
            ref="formAdd"
            v-model:form-data="formData"
            :rules="rules"
            @validateSuccess="validateSuccess"
        >
            <a-form-item label="部门名称" name="departName" placeholder="请输入应用名称">
                <a-input v-model:value.trim="formData.departName"/>
            </a-form-item>
            <a-form-item label="部门编号" name="departCode" placeholder="请输入应用编号">
                <a-input v-model:value.trim="formData.departCode"/>
            </a-form-item>
            <a-form-item label="备注" name="remark" placeholder="请输入应用编号">
                <a-input v-model:value.trim="formData.remark"/>
            </a-form-item>
        </v-form-layout>
    </v-dialog-layout>
</template>

<script>
  import { addRules } from './config';
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
  import { message } from 'ant-design-vue';
  export default {
    name: 'add',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      initForm: {
        type: Object
      }
    },
    setup(props, { emit }) {
      const {proxy} = getCurrentInstance()
      let formAdd = ref();
      const formData = reactive({
        id: '',
        departName: '',
        departCode: '',
        remark: '',
        enabled: 1
      });
      const rules = addRules

      onMounted(() => {
        if (props.initForm) {
          for (let item in formData) {
            formData[item] = props.initForm[item]
          }
          formData.id = props.initForm['id']
        }
      })

      const validateSuccess = () => {
        if (formData.id) {
          proxy.$http.post(proxy.$api.department.update, formData).then(res => {
            message.success('更新成功')
            emit('update:visible', false)
            emit('close', false)
          }).catch(err => {
          })
        } else {
          delete formData['id']
          proxy.$http.post(proxy.$api.department.add, formData).then(res => {
            message.success('添加成功')
            emit('update:visible', false)
            emit('close', false)
          }).catch(err => {
          })
        }
      };

      const cancel = () => {
        emit('update:visible', false)
      };

      return {
        cancel,
        validateSuccess,
        formData,
        rules,
        formAdd
      }
    }
  }
</script>

<style scoped>

</style>